

var cookie = require("cookie")
,   session = require("express-session");

/**
 * All socket IO events that can be emitted by the client
 * @param {[type]} socket [description]
 */
exports.SocketOnConnection = function(socket) {

	var handshake = socket.handshake
	,	sessionID = handshake.sessionID
	,	meetingID = handshake.meetingID;
	;

    // parse cookies
    handshake.cookies = cookie.parse(handshake.headers.cookie);
    handshake.filter = {};

    socket.join( "web" );

    var clientOnDecoded = socket.client.ondecoded;
    socket.client.ondecoded = function(data){
        console.dir(data);
        return clientOnDecoded(data);
    }

    socket.emit('connected', {address: handshake.address} );

    // 筛选
    socket.on("filter",function(fltstr){
        var filter = fltstr.split(":");
        var field = '';
        switch(filter[0].toLowerCase())
        {
            case "serverip": field="serverIP"; break;
            case "clientip": field="clientIP"; break;
            case "useragent": field="userAgent"; break;
            case "host": field= "host"; break;
            case "httpmethod": field="httpMethod"; break;
            case "requesturi": field="requestURI";break;

            case "cookie":
                if(!handshake.filter.cookies) handshake.filter.cookies = {};
                var cookiesp = filter[1].split("=");
                handshake.filter.cookies[cookiesp[0]]=cookiesp[1];
                break;
        }
        if(field) handshake.filter[field] = filter[1];
        socket.emit("upadateFilter", handshake.filter );
    });


    /** 断开来连接 */
    socket.on('disconnect', function () {

    });
  
};


function dispatchFilter(socket, data){
    var filter = socket.handshake.filter;
    // 保存线程记录
    if(!socket.handshake.threads) socket.handshake.threads = {};
    // 已筛选通过的线程
    if( socket.handshake.threads[ data.thread.split("_")[0] ] ){
        // 线程结束信号
        if(data.type.toLowerCase()=="threadend") delete socket.handshake.threads[data.thread];
        return true;
    }

    var hasfilter = false;
    var dcookies = cookie.parse(typeof data.cookie=="string"?data.cookie:"");
    for(var p in filter){
        hasfilter = true;
        switch(p){
            case "cookies":
                for(var c in filter.cookies){
                    if( !(new RegExp(filter.cookies[c])).test(dcookies[c]) ) return false;
                }
                break;
            default:
                if( !(new RegExp(filter[p])).test(data[p]) ) return false;
        }
    }
    // 无筛选条件
    if(!hasfilter) return false;

    // 保存筛选通过的线程
    if(data.type.toLowerCase() == "threadstart"){
        socket.handshake.threads[data.thread] = 1;
    }
    
    return true;
}


exports.webPublish = function(action, data){

    // 遍历客户端, 根据filter发送消息
    io.to("web").sockets.forEach(function(socket, i){
        if( dispatchFilter(socket, data) ){
            socket.emit(action, data );
        }
    })

    //io.to("web").emit( action, data );
}